import LoginStore from '../pages/login/store.js';
const app =getApp();

const proxy = 'https://500px.com.cn';
// const proxy = 'https://photo-test-community.shijue.me';

const reqHeader = {
  PF500MClient: 'wechatapplets',
  PF500MClientVersion: '0'
};

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatDate = (date, format = '.') => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate();
  return [year, month, day].map(formatNumber).join(format)
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
const calcTime = uploadTime => {
    let curDate = new Date();
    let curYear = curDate.getFullYear();
    let curMonth = curDate.getMonth();
    let curday = curDate.getDate();
    let curHour = curDate.getHours();
    let curMin = curDate.getMinutes();

    let uploadYear = uploadTime.getFullYear();
    let uploadMonth = uploadTime.getMonth();
    let uploadDate = uploadTime.getDate();
    let uploadHour = uploadTime.getHours();
    let uploadMin = uploadTime.getMinutes();

    if ((curYear - uploadYear) > 0) {
        return {
            key: '年前',
            num: curYear - uploadYear
        }
    } else if ((curMonth - uploadMonth) > 0) {
        return {
            key: '个月前',
            num: curMonth - uploadMonth
        }
    } else if ((curday - uploadDate) > 0) {
        return {
            key: '天前',
            num: curday - uploadDate
        }
    } else if ((curHour - uploadHour) > 0) {
        return {
            key: '小时前',
            num: curHour - uploadHour
        }
    } else if ((curMin - uploadMin) > 0) {
        return {
            key: '分钟前',
            num: curMin - uploadMin
        }
    } else {
        return {
            key: '刚刚',
            num: ''
        }
    }
}

const getscene = (paramStr,callback) => {
  wx.request({
    url: `${proxy}/wxsoft/applets/getscene`,
    data: {
      paramStr: paramStr
    },
    method: 'POST',
    header: Object.assign({
      'content-type': 'application/x-www-form-urlencoded'
    }, reqHeader),
    success: function (res) {
      if (res.statusCode != 200) {
        return;
      }
      if (res.data.status == 200) {
        res = res.data;

        callback(res.data.scene);

      } else {
        console.log(res.data.message);
      }
    },
    fail: function (e) {
      cosnole.log(e);
    }
  });
}

const getparamstr = (scene, callback) => {
  wx.request({
    url: `${proxy}/wxsoft/applets/getparamstr`,
    data: {
      scene: scene
    },
    header: reqHeader,
    success: function (res) {
      if (res.statusCode != 200) {
        return;
      }
      if (res.data.status == 200) {
        res = res.data;

        callback(res.data.paramStr);

      } else {
        console.log(res.data.message);
      }
    },
    fail: function (e) {
      cosnole.log(e);
    }
  });
}

const limitLength = (str)=>{
  if (str.length > 14) {
    str = str.substr(0, 14);
    str = str + '...';
  }
  return str;
}

const isAuthorization = (e)=>{
  if(e == undefined){
    return true;
  }
  if (e.detail.errMsg == "getUserInfo:fail auth deny") {
    //拒绝
    return false
  } else {
    return true;
  }
}

const followAction = (e, me, userInfo, fromKey,callback,resback) => {
  if (!isAuthorization(e)) {
    return;
  }
  LoginStore.validateLogin(() => {

    if (userInfo.userFolloweeState == undefined) {
      callback();
      return;
    }

    if (fromKey === "socialList"){
      wx.showLoading({
        title: 'loading...',
        mask:true
      })
    }

    let userAccountInfo = LoginStore.userInfo;
    let actionFlag = 1;
    if (userInfo.userFolloweeState) {
      actionFlag = 0;
    }
    wx.request({
      url: `${proxy}/community/doFollow.do`,
      data: {
        action: actionFlag,
        followerId: userInfo.id,
        access_token: userAccountInfo.access_token
      },
      header: reqHeader,
      success: function (res) {
        res = res.data;
        if (res.status == 200) {
          if (userInfo.userFolloweeState) {
            userInfo.userFollowedCount--;
          } else {
            userInfo.userFollowedCount++;
          }
          userInfo.userFolloweeState = !userInfo.userFolloweeState;
          resback();
          
        } else {
          console.log(res.message);
        }

      }
    });
  })
}

const greedoLayout = (listData)=>{
  let mContentWidth = app.globalData.screenWidth;
  let mMaxRowHeight = 200

  let currentRowHeight = mMaxRowHeight
  let row = 0
  let pos = 0
  let currentRowAspectRatio = 0.0
  let size = listData.length
  let itemAspectRatios = []
  let itemAspectRatiosIndex = []
  for (let i = 0; i < size; i++) {
    let width = listData[i].width || 355;
    let height = listData[i].height || 200;
    listData[i].aspectRatio = width / height
  }

  while (pos < size) {
    let posAspectRatio = listData[pos].aspectRatio
    currentRowAspectRatio += posAspectRatio
    itemAspectRatios.push(posAspectRatio)
    itemAspectRatiosIndex.push(pos)


    currentRowHeight = calculateHeight(mContentWidth, currentRowAspectRatio)

    let isRowFull = currentRowHeight <= mMaxRowHeight

    if (isRowFull) {
      let rowChildCount = itemAspectRatios.length

      let availableSpace = mContentWidth
      for (let i = 0; i < rowChildCount; i++) {
        let itemWidth = calculateWidth(currentRowHeight, itemAspectRatios[i])
        if (itemWidth > availableSpace) {
          itemWidth = availableSpace
        }
        listData[itemAspectRatiosIndex[i]].width2 = itemWidth - 4
        listData[itemAspectRatiosIndex[i]].height2 = currentRowHeight - 4
        availableSpace -= itemWidth
      }
      itemAspectRatios = []
      itemAspectRatiosIndex = []
      currentRowAspectRatio = 0.0
    } else {
      if (pos == size - 1) {
        let rowChildCount = itemAspectRatios.length
        if (rowChildCount == 1) {
          let itemWidth = calculateWidth(mContentWidth / 3, itemAspectRatios[0])
          listData[itemAspectRatiosIndex[0]].width2 = itemWidth - 4
          listData[itemAspectRatiosIndex[0]].height2 = mContentWidth / 3 - 4
        } else {
          let availableSpace = mContentWidth
          for (let i = 0; i < rowChildCount; i++) {
            let itemWidth = calculateWidth(mMaxRowHeight, itemAspectRatios[i])
            if (itemWidth > availableSpace) {
              itemWidth = availableSpace
            }
            listData[itemAspectRatiosIndex[i]].width2 = itemWidth - 4
            listData[itemAspectRatiosIndex[i]].height2 = mMaxRowHeight - 4
            availableSpace -= itemWidth
          }
        }
      }
    }
    pos++
  }
}

const calculateWidth = (itemHeight, aspectRatio) => {
  return parseInt(Math.ceil(itemHeight * aspectRatio))
}

const calculateHeight = (itemWidth, aspectRatio)=> {
  return parseInt(Math.ceil(itemWidth / aspectRatio))
}

const banPNG = (path) => {
  for (let imgUrl of path) {
    if (imgUrl.search('.png') != -1) {
      wx.showModal({
        title: '提示',
        content: '目前仅支持上传jpg、jpeg格式的图片',
        showCancel: false
      });
      return false;
    }
  }

  return true
}

const maiDian = (objId,callback)=>{
  wx.request({
    url: `${proxy}/alilog/put`,
    data: {
      objId: objId,
      access_token: LoginStore.userInfo.access_token
    },
    header: reqHeader,
    success: function (data) {
      callback(data);
    },
    fail: function (e) {
      console.log(e, '埋点失败');
    }
  })
}

const roundRect = (ctx, x, y, w, h, r, color) => {
  // 开始绘制
  ctx.beginPath()
  // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
  // 这里是使用 fill 还是 stroke都可以，二选一即可
  ctx.setFillStyle(color)
  // ctx.setStrokeStyle('transparent')
  // 左上角
  ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

  // border-top
  ctx.moveTo(x + r, y)
  ctx.lineTo(x + w - r, y)
  ctx.lineTo(x + w, y + r)
  // 右上角
  ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

  // border-right
  ctx.lineTo(x + w, y + h - r)
  ctx.lineTo(x + w - r, y + h)
  // 右下角
  ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

  // border-bottom
  ctx.lineTo(x + r, y + h)
  ctx.lineTo(x, y + h - r)
  // 左下角
  ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

  // border-left
  ctx.lineTo(x, y + r)
  ctx.lineTo(x + r, y)

  // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
  ctx.fill()
  // ctx.stroke()
  // ctx.closePath()
}

module.exports = {
  stringify: function (jsonObj) {
      return encodeURIComponent(JSON.stringify(jsonObj));
  },
  reqHeader: reqHeader,
  ossuploadurl: 'https://img.500px.me',
  proxy: proxy,//'https://500px.com.cn',//'https://photo-test-community.shijue.me',
  formatTime: formatTime,
  calcTime: calcTime,
  getscene: getscene,
  getparamstr: getparamstr,
  limitLength: limitLength,
  isAuthorization: isAuthorization,
  formatDate: formatDate,
  followAction: followAction,
  greedoLayout: greedoLayout,
  banPNG: banPNG,
  maiDian: maiDian,
  roundRect: roundRect
}
